<?php
namespace app\api\controller;
use app\common\model as M;

/**
 *
 */
class Order extends \app\api\ApiAuth
{
    public $model = '\app\common\model\Order';
	
    /**
     * 商城兑换订单
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
	public function mall()
	{
		$filter = input();
		$filter['uid'] = $this->uid;
		return $this->returnSuccess(M\OrderOuterExchange::orderList($filter));
	}

	/**
	 * 商城订单确认收货
	 * @Author   FW
	 * @DateTime 2024-03-27
	 * @Email    123763712@qq.com
	 * @return   [type]           [description]
	 */
	public function mallRecive()
	{
		$order_id        = (int)$this->request->post('order_id');
		if ( $order_id > 0 ) {
			$order_outer_id = M\Order::where('id',$order_id)->value('order_outer_id');
			$res = M\OrderOuterExchange::where('id' , $order_outer_id)->update(['status' => M\OrderOuterExchange::TYPE_RECIIVED]);
			if ( $res ) return $this->returnSuccess();
		}

		return $this->returnFail('操作失败');
	}

    /**
     * 线路预定订单
     * @Author   FW
     * @DateTime 2024-03-19
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function routers()
    {
        $filter = input();

        $sales_admin = $filter['sales_admin'] ?? 0;
        $sales_admin_id = M\User::calcSalesAdminId($this->uid);

        if ( $sales_admin == 1 ) {
        	$filter['sales_admin_id'] = $sales_admin_id;
        } else {
        	 if ( isset($filter['uid']) ) {
	        	if ( $sales_admin_id > 0 ) {
	        		$filter['uid'] = $filter['uid'];
	        	}
	        }

	        ## 默认只能查询用户自己名下的线路
	        if ( !isset($filter['uid']) || empty($filter['uid']) ) $filter['uid'] = $this->uid;
        }


        return $this->returnSuccess(M\OrderOuterRoutes::orderList($filter));
    }

    /**
     * 订单支付
     * @Author   FW
     * @DateTime 2021-05-17
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function payment ()
    {
        $order_id        = (int)$this->request->post('order_id');

        ## 获取订单信息
        $order = M\Order::alias('o')
            ->field("o.id,o.id as order_id,o.order_no,o.status,o.pay_type,o.pay_status,o.uid,o.order_amt,o.golds,o.description,o.use_deposit,o.deposit_amt,o.final_amt")
            ->where(['o.id' => $order_id])
            ->find();

        if( !empty($order) ){
            if( $order->pay_status == 1 ) return $this->returnFail('订单已支付!');

            ## 需要支付金币的订单：检查用户金币余额是否足够
            if ( $order->golds > 0 ) {
                $userGoldsBalance = M\User::where('uid',$this->uid)->value('golds');
                if ( $order->golds > $userGoldsBalance ) return $this->returnFail('用户金币余额不足！');
            }


            if ( $order->order_amt > 0 ) {
            	$pay_params = [];
                // 微信支付
                if ( $order->pay_type == M\Order::PAY_WECHAT ) {
                	$order_amt    = $order->order_amt;
                	$description  = $order->description;
                	$out_trade_no = $order->order_no;

                	## 使用定金的订单
                	if ( $order->use_deposit == 1 ) {
                		// 支付定金
                		if ( $order->status == 0 ) {
                			$order_amt   = $order->deposit_amt;
                			$description = '【定金】' . $description;
                			$out_trade_no= M\OrderSubs::where('order_id',$order_id)->where('order_type',1)->value('order_no');
                		}

                		// 支付尾款
                		if ( $order->status == 3 ) {
                			$order_amt   = $order->final_amt;
                			$description = '【尾款】' . $description;
                			$out_trade_no= M\OrderSubs::where('order_id',$order_id)->where('order_type',2)->value('order_no');
                		}
                	}
                	
                	$pay_params = (new \service\WechatPayV3Service)->jsapi($out_trade_no, $order_amt, $description, $openid=$this->userInfo['openid']);
                }

                return $this->returnSuccess(['pay_status' => 0,'pay_type' => $order->pay_type, 'pay_params' => $pay_params]);
            }

            ## 不须唤起支付的订单
            if ( $order->order_amt <= 0 ) {
                M\Order::paySuccess($order_no = $order->order_no, $out_trade_no = '1001' . date('YmdHis') . mt_rand(1000,9999));
                return $this->returnSuccess(['pay_status' => 1]);
            }
        }
        return $this->returnFail('订单支付失败!');
    }

    /**
     * 创建订单 购买订单，金额统计还得规划下。因为购买的订单还未消费，如果统计总额时算上的话，那么消费后会再算一遍，导致总额重复
     * @return   [type]           [description]
     */
    public function create ()
    {
        $order_info = input();
        if ( empty($order_info) ) return $this->returnFail('创建订单失败【0901】');

        ## 检测用户信息
        if ( !$this->uid ) return $this->returnFail('请先登录,再进行后续操作');
        $discount  = 1;

        $this->model::beginTrans();

        try {
            $order_type  = $order_info['order_type'] ?? 0;
			if ( !$order_type ) exception('订单类型异常【0902】');
			
			/** 初始化必要参数 **/
			$order_outer_id = $orgn_amt = $integral = $golds = $deposit_amt = $final_amt = 0;
			$description = '';
			$use_deposit  = $order_info['use_deposit'] ?? 0;

			$order_instance = null;

            ## 线路预定订单
            if ( $order_type == M\Order::ORDER_TYPE_ROUTES ) {
                $route_id    = $order_info['route_id'] ?? 0;
                $sku_id      = $order_info['sku_id'] ?? 0;
                $date        = $order_info['date'] ?? 0;
                $nums        = $order_info['nums'] ?? 1;
                $double_room = $nums; $big_room = 0;
                if ( $nums > 2 ) {
	                $big_room    = $nums % 2;
	            	$double_room = ($nums - $big_room) / 2;
	            }

				if ( empty($route_id) || empty($sku_id) || empty($date) ) exception('线路预定信息不详【0902】');
				
				$res = M\OrderOuterRoutes::create([
					'route_id'    => $route_id,
					'sku_id'      => $sku_id,
					'date'        => $date,
					'nums'        => $nums,
					'double_room' => $double_room,
					'big_room'    => $big_room,
				]);
				if ( !isset($res->id) ) exception('线路预定信息出错【0903】');
				$order_outer_id = $res->id;
				
				$currentLevelId = 0;
		        if ( $this->uid > 0 ) $currentLevelId = M\User::where('uid',$this->uid)->value('level_id');

		        $body = M\RoutesSkuPrice::alias('t1')->field('r.route_name,r.support_deposit,s.sku_name,ifnull(t2.level_price,0) as price')
		        ->join('__ROUTES_SKU_PRICE_PRIME__ t2','t1.route_id=t2.route_id AND t1.id=t2.skp_id AND t2.level_id='.$currentLevelId)
		        ->join('__ROUTES__ r','t1.route_id=r.id')
				->join('__ROUTES_SKU__ s','t1.sku_id=s.id')
		        ->where(['t1.route_id' => $route_id,'t1.sku_id' => $sku_id , 't1.date' => $date])
		        ->find();
		        if ( empty($body) ) exception('查找SKU价格配置失败【0904】');

				$orgn_amt = bcmul($body->price , $nums,2);
				if ( !$orgn_amt ) exception('线路预定价格计算出错【0904】');
				
				$description = '预定线路,规格明细：'.$body->sku_name.'，日期：'.date('m月d日',strtotime($date));

				// 使用定金功能（拆分为定金、尾款子订单）
				if ( $use_deposit > 0 ) {
					if ( $body->support_deposit != 1 ) exception('线路不支持定金功能【0904】');
					$depositCfg = M\RoutesDespositCfg::where('route_id' , $route_id)->find();
					if ( empty($depositCfg) ) exception('无有效的定金配置【0904】');

					if ( $nums < $depositCfg->min_people ) exception(sprintf('使用定金最少预定人数为%d人',$depositCfg->min_people));

					$deposit_amt = bcmul($depositCfg->deposit_amt,$nums,2);
					$final_amt   = bcsub($orgn_amt , $deposit_amt , 2);
				}

				$order_instance = new M\order\RoutesBook;
            }
			
			## 金币商城订单
			if ( $order_type == M\Order::ORDER_TYPE_GOLDS ) {
				$goodsId   = $order_info['goods_id'] ?? 0;
				$addressId = $order_info['address_id'] ?? 0;
				$nums      = $order_info['nums'] ?? 1;
				
				if ( empty($goodsId) ) exception('兑换信息不详【0902】');
				
				$goodsInfo = M\GoldsGoods::where('id' , $goodsId)->find();
				if ( empty($goodsInfo) ) exception('兑换商品不存在【0903】');
				
				if ( $nums > $goodsInfo->goods_store ) exception('兑换商品库存不足');
				if ( $nums > $goodsInfo->max_nums ) exception('超过最大可兑换数量');
				
				$description = '兑换商品';
				
				// 纯金币购买
				if ( $goodsInfo->pay_type == M\GoldsGoods::PAY_GOLDS ) {
				    $golds = bcmul($goodsInfo->goods_golds , $nums, 0);
					
					## 检查用户金币是否足够
					$userGolds = M\User::where('uid',$this->uid)->value('golds');
					if ( $golds > $userGolds ) exception('金币余额不足');
				}
				
				// 金币+钱购买
				if ( $goodsInfo->pay_type == M\GoldsGoods::PAY_GOLDS_RMB ) {
				    $golds    = bcmul($goodsInfo->goods_golds , $nums, 0);
					$orgn_amt = bcmul($goodsInfo->goods_price , $nums, 2);
					
					## 检查用户金币是否足够
					$userGolds = M\User::where('uid',$this->uid)->value('golds');
					if ( $golds > $userGolds ) exception('金币余额不足');
				}
				
				// 纯钱购买
				if ( $goodsInfo->pay_type == M\GoldsGoods::PAY_RMB ) {
				    $orgn_amt = bcmul($goodsInfo->goods_price , $nums, 2);
				}
				
				## 01 生成子订单
				$res = M\OrderOuterExchange::create([
				    'goods_id'   => $goodsInfo->id,
				    'address_id' => $addressId,
				    'uid'        => $this->uid,
				    'nums'       => $nums
				]);
				if ( !isset($res->id) ) exception('线路预定信息出错【0903】');
				$order_outer_id = $res->id;
				
				$order_instance = new M\order\GoldsGoods;
			}
			
			## 会员开通订单
			if ( $order_type == M\Order::ORDER_TYPE_OPENCARD ) {
				$levelId   = $order_info['id'] ?? 0;

				$levelInfo = M\UserLevel::where('id',$levelId)->find();
				if ( empty($levelInfo) ) exception('等级不存在【0903】');
				$levelInfo->grade_type_display = M\UserLevel::$grade_type[$levelInfo->grade_type] ?? '-';

				$description = sprintf("会员开通：%s，期限%d天",$levelInfo->grade_type_display,$levelInfo->days);
				$orgn_amt  = $levelInfo->price;

				## 检查是否存在未完成的开通记录
				$order_outer_id = M\UserLevelRecords::where(['uid'=>$this->uid,'level_id'=>$levelInfo->id,'type'=>M\Order::ORDER_TYPE_OPENCARD])->value('id');
				if ( !$order_outer_id ) {
					## 生成子订单（用户会员等级记录）
					$res = M\UserLevelRecords::create([
						'uid'         => $this->uid,
					    'level_id'    => $levelInfo->id,
					    'expire_date' => date('Y-m-d',strtotime(sprintf("+%d days" , $levelInfo->days))),
					    'obtain_date' => date('Y-m-d'),
					    'type'        => M\Order::ORDER_TYPE_OPENCARD
					]);

					$order_outer_id = $res->id ?? 0;
					if ( !$order_outer_id ) exception('等级记录出错【0908】');
				}

				$order_instance = new M\order\UserActivate;
			}

			## 会员升级订单
			if ( $order_type == M\Order::ORDER_TYPE_RAISE ) {
				$levelId   = $order_info['id'] ?? 0;

				$levelInfo = M\UserLevel::where('id',$levelId)->find();
				if ( empty($levelInfo) ) exception('等级不存在【0903】');
				$levelInfo->grade_type_display = M\UserLevel::$grade_type[$levelInfo->grade_type] ?? '-';

				$description = sprintf("会员升级：%s，期限%d天",$levelInfo->grade_type_display,$levelInfo->days);

				$refundInfo  = M\UserLevel::calcUserLevelRefund($this->uid);
            	$levelInfo->price = bcsub($levelInfo->price,$refundInfo['leftAmt'],2);

				$orgn_amt  = $levelInfo->price;

				## 检查是否存在未完成的升级记录
				$order_outer_id = M\UserLevelRecords::where(['uid'=>$this->uid,'level_id'=>$levelInfo->id,'type'=>M\Order::ORDER_TYPE_RAISE])->value('id');
				if ( !$order_outer_id ) {
					## 生成子订单（用户会员等级记录）
					$res = M\UserLevelRecords::create([
						'uid'         => $this->uid,
					    'level_id'    => $levelInfo->id,
					    'expire_date' => date('Y-m-d',strtotime(sprintf("+%d days" , $levelInfo->days))),
					    'obtain_date' => date('Y-m-d'),
					    'type'        => M\Order::ORDER_TYPE_RAISE
					]);

					$order_outer_id = $res->id ?? 0;
					if ( !$order_outer_id ) exception('等级记录出错【0908】');
				}

				$order_instance = new M\order\UserRaise;
			}

			## 会员续费订单
			if ( $order_type == M\Order::ORDER_TYPE_RENEW ) {
			}

			if ( strlen($description) > 127 ) exception('error【0906】');
			if ( !$order_instance ) exception('获取订单对象异常【0907】');

            ## 01 创建订单
            $order['orgn_amt']       = $orgn_amt;
            $order['disc_amt']       = 0;
            $order['order_amt']      = $order['orgn_amt'] - $order['disc_amt'];
			$order['integral']       = $integral;
			$order['golds']          = $golds;
            $order['uid']            = $this->uid;
            $order['order_type']     = $order_type;
            $order['pay_type']       = M\Order::PAY_WECHAT;
            $order['order_outer_id'] = $order_outer_id;
            $order['description']    = $description;
            $order['use_deposit']    = $use_deposit;
            $order['deposit_amt']    = $deposit_amt;
            $order['final_amt']      = $final_amt;
            $order['spread_uid']     = $this->spread_uid;
            $order['spread_suid']    = $this->spread_suid;
            $orderObj = $order_instance::create_order($order);
            if ( !isset($orderObj->id) ) exception('创建订单失败【0902】');

            $order['order_id']       = $orderObj->id;
            $this->model::commitTrans();
            return $this->returnSuccess($order);
        } catch ( \Exception $e ) {
            $this->model::rollbackTrans();
            return $this->returnFail($e->getMessage());
        }

        $this->model::rollbackTrans();
        return $this->returnFail('操作失败');
    }

    /**
     * 删除订单
     * @Author   FW
     * @DateTime 2021-05-17
     * @Email    123763712@qq.com
     * @param    [type]           $order_id [description]
     * @return   [type]                    [description]
     */
    public function del_order ( $order_id )
    {
    	$res = $this->model::deleteOne($order_id);

    	if ( $res === false ) return $this->returnFail('删除订单失败');

    	return $this->returnSuccess([]);
    }
}//Class End